package com.gravata.enigma.reader;

import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;

import com.gravata.enigma.FtpHelper;
import com.gravata.enigma.PublishMessage;
import com.gravata.enigma.R;
import com.gravata.enigma.activities.TelaInicial;
import com.gravata.enigma.model.FEC;
import com.gravata.enigma.model.Flags;
import com.gravata.enigma.model.Modulacao;
import com.gravata.enigma.model.Pilot;
import com.gravata.enigma.model.Polarization;
import com.gravata.enigma.model.Rolloff;
import com.gravata.enigma.model.Satelite;
import com.gravata.enigma.model.Sistema;
import com.gravata.enigma.model.Transponder;


public class ParseSatelites {

	private static Map<Satelite, List<Transponder>> satTransponders=new HashMap<Satelite, List<Transponder>>();
	private static PublishMessage listener;
	private static Context context;
	public static void parse(Context context,PublishMessage listener) {
			ParseSatelites.context=context;
			ParseSatelites.listener=listener;
			List<Satelite> satelites=new ArrayList<Satelite>();
			FtpHelper ftpHelper=new FtpHelper(context);

			try {
				ftpHelper.connect();
			} catch (Exception e1) {
				listener.publish(context.getString(R.string.ftp_error_conexao));
				try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return ;
			}

			ParseSatelites.listener.publish(context.getString(R.string.parse_satelite_lendo_arquivo));
	        InputStream istream = ftpHelper.getFileStream(TelaInicial.profile.getSatelitePath());
	        try{

	        	TelaInicial.repositorioSatelite.excluir(TelaInicial.profile);

	            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
	                    .newDocumentBuilder();

	            Document doc = builder.parse(istream);

	            doc.getDocumentElement().normalize();


	        	NodeList nList = doc.getElementsByTagName("sat");


	        	for (int temp = 0; temp < nList.getLength(); temp++) {

	        		Node nNode = nList.item(temp);

	        		if (nNode.getNodeType() == Node.ELEMENT_NODE) {

	        			Element eElement = (Element) nNode;

	        			createSatelite(eElement);

	        		}
	        	}
	           }catch(Exception e){
	        	   e.printStackTrace();
	        }

	        ftpHelper.disconnect();

	}

	private static void createSatelite(Element element){
		//<sat flags="0" name="VIVO TV (61W)" position="-610">
		Satelite satelite=new Satelite();

		satelite.setPosition(Integer.parseInt(element.getAttribute("position")));
		satelite.setName(element.getAttribute("name"));
		satelite.setProfile(TelaInicial.profile);
		if(element.getAttribute("flags")!=null)
			satelite.setFlags(Flags.values()[Integer.parseInt(element.getAttribute("flags"))]);

		ParseSatelites.listener.publish(context.getString(R.string.parse_satelite_inserindo_sat)+ " "+satelite.getName());
		try {
			TelaInicial.repositorioSatelite.inserir(satelite);

			NodeList nList= element.getElementsByTagName("transponder");
			for (int temp = 0; temp < nList.getLength(); temp++) {

	    		Node nNode = nList.item(temp);

	    		if (nNode.getNodeType() == Node.ELEMENT_NODE) {
	    			Transponder transponder=createTransponder(nNode);
	    			transponder.setSatelite(satelite);

	    			ParseSatelites.listener.publish(context.getString(R.string.parse_satelite_inserindo_tp)+ " "+transponder);
					TelaInicial.repositorioTransponder.inserir(transponder);
	    		}

			}

		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	private static Transponder createTransponder(Node node){
		//<transponder fec_inner="1" frequency="11910000" modulation="2" onid="56000" pilot="1" polarization="1" rolloff="1" symbol_rate="7200000" system="1" tsid="5000" />
		Transponder transponder=new Transponder();

		NamedNodeMap atributos= node.getAttributes();
		if(atributoExiste(atributos, "frequency"))
			transponder.setFrequency(Integer.parseInt(atributos.getNamedItem("frequency").getNodeValue()));
		if(atributoExiste(atributos, "symbol_rate"))
			transponder.setSymbolRate(Integer.parseInt(atributos.getNamedItem("symbol_rate").getNodeValue()));

		if(atributoExiste(atributos, "polarization")){
			transponder.setPolarization(Polarization.values()[Integer.parseInt(atributos.getNamedItem("polarization").getNodeValue())]);
		}

		if(atributoExiste(atributos, "fec_inner"))
			transponder.setFec(FEC.values()[Integer.parseInt(atributos.getNamedItem("fec_inner").getNodeValue())]);

		if(atributoExiste(atributos, "system"))
			transponder.setSystem(Sistema.values()[ Integer.parseInt(atributos.getNamedItem("system").getNodeValue())]);

		if(atributoExiste(atributos, "modulation"))
			transponder.setModulation(Modulacao.values()[ Integer.parseInt(atributos.getNamedItem("modulation").getNodeValue())]);

		if(atributoExiste(atributos, "pilot"))
			transponder.setPilot(Pilot.values()[ Integer.parseInt(atributos.getNamedItem("pilot").getNodeValue())]);

		if(atributoExiste(atributos, "rolloff"))
			transponder.setRolloff(Rolloff.values()[Integer.parseInt(atributos.getNamedItem("rolloff").getNodeValue())]);

		return transponder;

	}
	private static boolean atributoExiste(NamedNodeMap atributos,String atributo){
		return atributos.getNamedItem(atributo)!=null;
	}
}
